<template>
  <div>
    <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="150px">
      <div style="text-align:right" v-if="disabledFlag">
				<el-button @click="goback()" size="mini" type="primary" style="margin-right:50px">返回</el-button>
			</div>
      <div style="width: 500px;">
        <el-form-item label="优购券名称" prop="couponName">
          <el-input v-model="ruleForm.couponName" :disabled="disabledFlag" maxlength="30" type="textarea"
            show-word-limit  placeholder="请输入优购券名称" />
        </el-form-item>

        <el-form-item label="优购券使用规则" prop="couponUseRule">
          <el-input v-model="ruleForm.couponUseRule" :disabled="disabledFlag" type="textarea"
            maxlength="300" show-word-limit placeholder="请输入优购券使用规则" />
        </el-form-item>

        <el-form-item label="优购券分享标题" prop="couponShareTitle">
          <el-input v-model="ruleForm.couponShareTitle" :disabled="disabledFlag" placeholder="请输入优购券分享标题" />
        </el-form-item>
      </div>
      <el-form-item label="优购券分享图" prop="couponSharePicture">
        <el-upload
          :disabled="disabledFlag"
          :action="configServerUrl"
          :multiple="false"
          :limit="1"
          accept="image/jpeg,image/png"
          list-type="picture-card"
          :on-preview="handlePreview"
          :file-list="fileList"
          :on-success="(response) => { ruleForm.couponSharePicture = response.result }"
          :on-remove="() => { ruleForm.couponSharePicture = '' }"
          :on-exceed="() => { $message.warning('只能上传一张图片') }"
          :on-change="() => { submitForm('ruleForm') }"
        >
          <i class="el-icon-plus"></i>
        </el-upload>
        <p class="tips">
          注：上传图片(限5M)
          图片将用于分享图片的展示
        </p>
      </el-form-item>

      <div style="width: 500px">
        <el-form-item label="优购券有效期" prop="couponDate">
          <el-date-picker
            v-model="ruleForm.couponDate"
            type="daterange"
            align="right"
            unlink-panels
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd"
            :disabled="disabledFlag"
          />
        </el-form-item>
      </div>

      <el-form-item label="关联活动" prop="toActivity">
        <el-button type="primary" @click="showActivityDialog()" icon="el-icon-plus" size="mini"
          style="margin:5px 0 20px 0" v-if="!disabledFlag">添加活动
        </el-button>

        <div class="to-activity" v-if="activityDetail.activityName">
          <el-row>
            <el-col :span="8">
              <div class="to-activity-item">
                <div class="to-activity-item__label">活动名称：</div>
                <div class="to-activity-item__value">{{ activityDetail.activityName }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="to-activity-item">
                <div class="to-activity-item__label">活动编码：</div>
                <div class="to-activity-item__value">{{ activityDetail.activityCode }}</div>
              </div>
            </el-col>
            <el-col :span="8">
              <div class="to-activity-item">
                <div class="to-activity-item__label">活动类型：</div>
                <div class="to-activity-item__value">{{ activityDetail.activityType == 1 ? '定金预售' : '全款预售' }}</div>
              </div>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <div class="to-activity-item">
                <div class="to-activity-item__label">活动有效期：</div>
                <div class="to-activity-item__value">{{ activityDetail.beginDate }} 至 {{ activityDetail.endDate }}</div>
              </div>
            </el-col>
          </el-row>
          <el-button v-if="!disabledFlag" type="danger" size="mini" @click="() => { activityDetail = {} }">删除活动</el-button>
        </div>
      </el-form-item>

      <el-form-item label="适用门店" prop="yougouCouponStoreJoinDTOList">
        <el-button type="primary" @click="showShopDialog()" icon="el-icon-plus" size="mini"
          style="margin:5px 0 20px 0" v-if="!disabledFlag">添加门店
        </el-button>

        <el-table :data="ruleForm.yougouCouponStoreJoinDTOList" style="width:90%;" border :header-cell-style="{ background: '#eef1f6', color: '#606266' }">
          <el-table-column prop="authCode" label="授权码" width="180" header-align="center" />
					<el-table-column prop="storeName" label="店铺名称" header-align="center" />
          <el-table-column label="认购数量" width="180" header-align="center" align="center">
            <template slot-scope="scope">
              <el-input-number :min="1" v-model="scope.row.subscriptionQuantity" :disabled="disabledFlag" size="mini" />
            </template>
          </el-table-column>
          <el-table-column label="单人发券上限" width="180" header-align="center" align="center">
            <template slot-scope="scope">
              <el-input-number :min="1" v-model="scope.row.singleCouponLimit" :disabled="disabledFlag" size="mini" />
            </template>
          </el-table-column>
          <el-table-column v-if="!disabledFlag" label="操作" width="180" header-align="center" align="center">
            <template slot-scope="scope">
              <el-button
                icon="el-icon-delete"
                size="mini"
                type="text"
                @click="() => { ruleForm.yougouCouponStoreJoinDTOList.splice(scope.$index, 1) }"
              >删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>

      <el-form-item label="发布状态" prop="status">
				<el-radio-group v-model="ruleForm.status" :disabled="disabledFlag">
					<el-radio-button label="0">不发布</el-radio-button>
					<el-radio-button label="1">发布</el-radio-button>
				</el-radio-group>
			</el-form-item>

      <el-form-item style="width:100%;text-align:center">
				<el-button @click="goback()" v-show="!this.disabledFlag">取 消</el-button>
				<el-button type="primary" @click="submitForm('ruleForm')" v-show="!this.disabledFlag"
					:loading="submitLoading">保存
				</el-button>
			</el-form-item>
    </el-form>

    <!-- 图片预览 -->
    <el-dialog :visible.sync="dialogVisibleImg" title="图片预览">
      <img width="100%" :src="ruleForm.couponSharePicture">
    </el-dialog>
    
    <SelectActivity v-model="showActivity" @change="changeActivity" />
    <SelectShop v-model="showShop" :checkedList.sync="ruleForm.yougouCouponStoreJoinDTOList" @change="submitForm('ruleForm')" />
  </div>
</template>

<script>
import { addYougouCoupon, getYougouCouponInfo, setYougouCoupon } from "@/api/yougouCoupon";
import SelectActivity from './components/SelectActivity.vue';
import SelectShop from './components/SelectShop.vue';

export default {
  components: {
    SelectActivity,
    SelectShop
  },
  data() {
    return {
      configServerUrl: `${process.env.VUE_APP_BASE_API}/api/file-service/v1/file/uploadFile`,
      disabledFlag: false,
      ruleForm: {
        couponName: "",
        couponUseRule: "",
        couponShareTitle: "",
        couponSharePicture: "",
        couponDate: "",
        toActivity: null,
        yougouCouponStoreJoinDTOList: [],
        status: "0"
      },
      rules: {
        couponName: [
          { required: true, message: "请输入优购券名称", trigger: "blur" }
        ],
        couponUseRule: [
          { required: true, message: "请输入优购券使用规则", trigger: "blur" }
        ],
        couponShareTitle: [
          { required: true, message: "请输入优购券分享标题", trigger: "blur" }
        ],
        couponSharePicture: [
          { required: true, message: "请上传优购券分享图", trigger: "change" }
        ],
        couponDate: [
          { type: 'array', required: true, message: "请选择优购券有效期", trigger: "blur" }
        ],
        toActivity: [
          { required: true, message: "请选择关联活动", trigger: "change" }
        ],
        yougouCouponStoreJoinDTOList: [
          { type: 'array', required: true, message: "请选择适用门店", trigger: "change" }
        ],
        status: [
          { required: true, message: "请选择发布状态", trigger: "change" }
        ]
      },

      fileList: [],
      dialogVisibleImg: false,
      submitLoading: false,

      // 关联活动相关参数
      activityDetail: {},
      showActivity: false,

      // 关联店铺
      showShop: false
    }
  },

  created() {
    if(this.$route.params.type === 'detail'){
      this.disabledFlag = true;
    }
    if(this.$route.params.uuid) {
      this.getDetail(this.$route.params.uuid, this.$route.params.activityId)
    }
  },

  methods: {
    getDetail(uuid, activityId) {
      getYougouCouponInfo({
        activityId,
        uuid
      }).then(res => {
        if(res.code == 1) {
          this.ruleForm = res.result;
          this.fileList = [{ url: res.result.couponSharePicture }];
          this.ruleForm.couponDate = [res.result.couponBeginDate, res.result.couponEndDate];
          this.activityDetail = res.result.presaleActivityInfoDTOList[0];
          this.ruleForm.toActivity = res.result.presaleActivityInfoDTOList[0];
        } 
      })
    },
    goback() {
      this.$router.go("-1");
    },

    showActivityDialog() {
      this.showActivity = true;
    },

    changeActivity(detail) {
      this.activityDetail = detail;
      this.ruleForm.toActivity = detail;
      this.submitForm('ruleForm');
    },

    showShopDialog() {
      this.showShop = true;
    },

    handlePreview() {
      !this.ruleForm.couponSharePicture && (this.ruleForm.couponSharePicture = file.url);
      this.dialogVisibleImg = true;
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          const data = {
            ...this.ruleForm,
            couponBeginDate: this.ruleForm.couponDate[0],
            couponEndDate: this.ruleForm.couponDate[1],
            activityId: this.ruleForm.toActivity.uuid,
          };
          
          if(this.ruleForm.yougouCouponStoreJoinDTOList.some(item => isNaN(item.subscriptionQuantity) || isNaN(item.singleCouponLimit))) {
            this.$message.warning("请填写认购数量或者单人发券上限");
            return;
          }

          this.submitLoading = true;

          if(this.$route.params.type == 'edit') {
            setYougouCoupon({
              ...data,
              uuid: this.$route.params.uuid
            }).then((res) => {
              if (res.code == 1) {
                this.$message.success("操作成功");
                this.goback();
              }
            }).finally(() => {
              this.submitLoading = false;
            })
          } else {
            addYougouCoupon(data).then((res) => {
              if (res.code == 1) {
                this.$message.success("操作成功");
                this.goback();
              }
            }).finally(() => {
              this.submitLoading = false;
            })
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.tips {
  margin-left: 10px;
  color: red;
  font-size: 12px;
}

.to-activity {
  width: 90%;
  background-color: #fff;
  padding: 10px 20px 20px;
}

.to-activity-item {
  display: flex;
  align-items: center;
  width: 100%;
  &__label {
    color: #909399;
  }
  &__value {
    flex: 1;
  }
}
</style>